<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1000px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :inline="true" :rules="rules">
      <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
      <div class="search-container">
        <el-form-item label="班级名称" prop="className">
          <el-input
            v-model="formData.className"
            placeholder="请填写班级名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="班级人数" prop="classPerson">
          <el-input
            v-model="formData.classPerson"
            placeholder="请填写班级人数"
            clearable
          />
        </el-form-item>
        <el-form-item label="班主任名称" prop="classTeacher">
          <el-input
            v-model="formData.classTeacher"
            placeholder="请填写班主任名称"
            clearable
          />
        </el-form-item>
      </div>
      <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button type="success" plain @click="handleAdd">
            <i-ep-plus />
            新增</el-button
          >
        </template>
        <div class="formTable">
          <el-table
            class="draggableTable"
            :data="formData.studentData"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column label="学生姓名" props="name">
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'studentData.' + $index + '.name'" -->
                <el-form-item
                  :prop="'studentData.' + $index + '.name'"
                  :rules="rules.name"
                >
                  <el-input v-model="row.name" />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column prop="sex" label="学生性别">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'studentData.' + $index + '.sex'"
                  :rules="rules.sex"
                >
                  <el-select v-model="row.sex" placeholder="请选择性别">
                    <el-option
                      v-for="item in sexOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="联系电话">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'studentData.' + $index + '.phone'"
                  :rules="rules.phone"
                >
                  <el-input v-model="row.phone" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="是否需要住校" align="center">
              <template #default="{ row }">
                <el-switch v-model="row.isLive" />
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="300"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.studentData.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-rank />
                  移动
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import Sortable from "sortablejs";
import request from "@/utils/request";

defineOptions({
  name: "AddRoleTable",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (props.visible) {
      // 阻止默认行为
      document.body.ondrop = function (event) {
        event.preventDefault();
        event.stopPropagation();
      };
      // 调用 table拖拽排序
      nextTick(() => {
        rowDrop();
      });
    }
  }
);

/** 下拉框数据 */
const sexOptions = [
  {
    value: "1",
    label: "男",
  },
  {
    value: "2",
    label: "女",
  },
  {
    value: "3",
    label: "未知",
  },
];

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  className: "",
  classPerson: "",
  classTeacher: "",
  id: "",
  studentData: [
    {
      id: "",
      sex: "",
      name: "",
      isLive: false,
      phone: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  className: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
  classPerson: [{ required: true, message: "请输入班级人数", trigger: "blur" }],
  classTeacher: [
    { required: true, message: "请输入班主任姓名", trigger: "blur" },
  ],
  name: [{ required: true, message: "请输入学生姓名", trigger: "blur" }],
  sex: [{ required: true, message: "请选择学生性别", trigger: "change" }],
  phone: [{ required: true, message: "请填写手机号码", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.studentData.splice(index, 1);
};

const studentData = {
  id: "",
  sex: "",
  name: "",
  isLive: false,
  phone: "",
};

/** 添加行 */
const handleAdd = () => {
  formData.studentData.push(studentData);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    if (newVal?.id) {
      Object.assign(formData, props.data);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.studentData = [studentData];
}

const loading = ref(false);

/** 角色保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/system/sysRole/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`${text}成功`);
      closeDialog();
      emit("reset-table");
    }
  });
}

// 行拖拽
function rowDrop() {
  let tbody: any = document.querySelector(
    ".draggableTable .el-table__body-wrapper tbody"
  );
  Sortable.create(tbody, {
    onEnd({ newIndex, oldIndex }) {
      const currRow = toRaw(formData.studentData).splice(oldIndex, 1)[0];
      console.log("currRow", currRow);
      // formData.studentData = [];
      formData.studentData.splice(newIndex, 0, currRow);
    },
  });
}
onMounted(() => {});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
</style>
